from django.shortcuts import render

# Create your views here.
from django.db.models import Q
import re, json, time, requests, os
from django.views import View

from NewFlowLogic.models import *
from Oa_system.models import Staffing
from administrative.models import *
from back_management.models import topic_meeting, VoteLeader, topic_sing, CommitteeTable
from finance.models import TravelApply, LeaveRequest
from ios_api.models import ScanCode
from logistics.MessagePushOperationRecords import RecordAndPush
from personal_center.models import User, ConferenceRoomSignee, ConferenceRoomApplication
from administrative.models import Company
from django.shortcuts import render, redirect, HttpResponse
from Administrative_office_system.utils.views import LoginRequiredMixin
from supervision_inspection.models import CommitteeAttendance, AttendedMeeting, CommitteeTopics, AttendedMeetingPeople, \
    MeetingRoomLeave, MeetingRoomLeaveRecord


class letter_from_superiors(View):
    def post(self, request):
        flow_id = request.POST.get("id", '')
        opinion_detail = request.POST.get("opinion_detail", '')
        approve = request.POST.get("approve", '')

        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "上级来文")
        except:
            pass

        obj = OfficialDocuments.objects.get(id=int(flow_id))

        if not obj.officialdocumentsauditrecord_set.filter(node=obj.state, state='unaudit', audit_people=request.user).count():
            returnData = {'code': 500, 'message': '当前节点已审批，请勿重复点击！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        if obj.version != '3':
            obj.audit_users_already.add(request.user)
            if obj.state == "one":
                obj.current_audit_users.clear()
                audit_record = obj.officialdocumentsauditrecord_set.filter(node='one', state='unaudit').first()
                if approve == "audit":
                    leader_prople = request.POST.get("leader_prople", '')
                    AuditPeople = User.objects.get(id=int(leader_prople))
                    OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, state="unaudit", audit_people=AuditPeople, node="two")
                    obj.current_audit_users.add(AuditPeople)
                    obj.leaders = AuditPeople
                    obj.state = "two"
                else:
                    obj.state = "eight"
                    obj.type = "f"
                    obj.current_audit_users.add(obj.apply_user)

            elif obj.state == "two":
                obj.current_audit_users.remove(request.user)
                audit_record = obj.officialdocumentsauditrecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
                if approve == "audit":
                    Distributors = request.POST.get("Distributors", '')
                    ReadingPersonnel = request.POST.get("ReadingPersonnel", '')
                    distributors_list = re.findall('\((.*?)\)', Distributors)
                    for i in distributors_list:
                        AuditPeople = User.objects.get(job_number=i)
                        if not OfficialDocumentsAuditRecord.objects.filter(official_documents_id=obj, state="unaudit", audit_people=AuditPeople, node="three").count():
                            OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, state="unaudit", audit_people=AuditPeople, node="three")

                    if not obj.current_audit_users.all().count():
                        two_already_step = []
                        all_two_step = obj.officialdocumentsauditrecord_set.filter(node='two')
                        for two_step in all_two_step:
                            if two_step.audit_people not in two_already_step:
                                OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, state="unaudit", audit_people=two_step.audit_people, node="four")
                        five_step = Company.objects.get(id=80).head_people if obj.apply_user.company.id == 80 else Company.objects.get(id=3).head_people
                        OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, state="unaudit", audit_people=five_step, node="five")
                        obj.state = "three"
                        all_three_step = obj.officialdocumentsauditrecord_set.filter(node='three')
                        for three_step in all_three_step:
                            obj.current_audit_users.add(three_step.audit_people)

                    items = []
                    receive_people = re.findall('\((.*?)\)', ReadingPersonnel)
                    receive_people_objs = User.objects.filter(job_number__in=receive_people, is_delete="0")
                    for receive_people_obj in receive_people_objs:
                        off_obj = OfficialDocumentsPeople(notice_id=obj, state='accept', audit_people=receive_people_obj)
                        items.append(off_obj)
                    OfficialDocumentsPeople.objects.bulk_create(items)

                elif approve == "end":
                    obj.state = "six"
                    obj.type = "e"

                else:
                    obj.state = "eight"
                    obj.type = "f"
                    obj.current_audit_users.add(obj.apply_user)

            elif obj.state == "three":
                audit_record = obj.officialdocumentsauditrecord_set.get(node='three', state='unaudit', audit_people=request.user)
                if approve == "audit":
                    obj.current_audit_users.remove(request.user)
                    audit_record.state = approve
                    audit_record.save()
                    Receipt = request.POST.get("Receipt", '')
                    audit_record.img_path = Receipt
                    if obj.officialdocumentsauditrecord_set.filter(node='three', state='unaudit').count():
                        obj.state = "three"
                    else:
                        obj.state = "four"
                        obj.type = "a"
                        all_four_step = obj.officialdocumentsauditrecord_set.filter(node='four')
                        for four_step in all_four_step:
                            obj.current_audit_users.add(four_step.audit_people)
                else:
                    obj.current_audit_users.clear()
                    obj.state = "eight"
                    obj.type = "f"
                    obj.current_audit_users.add(obj.apply_user)

            elif obj.state == "four":
                obj.current_audit_users.remove(request.user)
                audit_record = obj.officialdocumentsauditrecord_set.get(node='four', state='unaudit', audit_people=request.user)
                if approve == "audit":
                    if not obj.current_audit_users.all().count():
                        obj.state = "five"
                        five_step = obj.officialdocumentsauditrecord_set.filter(node='five', state='unaudit')
                        obj.current_audit_users.add(five_step.first().audit_people)
                else:
                    obj.state = "three"
                    obj.type = "f"
                    set_list = []
                    three_step = obj.officialdocumentsauditrecord_set.filter(node='three')
                    for step in three_step:
                        if step.audit_people not in set_list:
                            OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, state="unaudit", audit_people=step.audit_people, node="three")
                            obj.current_audit_users.add(step.audit_people)
                    OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, state="unaudit", audit_people=obj.leaders, node="four")

            else:
                obj.current_audit_users.clear()
                audit_record = obj.officialdocumentsauditrecord_set.get(node='five', state='unaudit', audit_people=request.user)
                if approve == "audit":
                    obj.state = "six"
                    obj.type = "e"
                else:
                    obj.state = "eight"
                    obj.current_audit_users.add(obj.apply_user)

            audit_record.update_time = datetime.datetime.now()
            audit_record.state = approve
            audit_record.audit_note = opinion_detail
            audit_record.save()
            obj.save()

        else:
            obj.audit_users_already.add(request.user)
            obj.current_audit_users.remove(request.user)
            if obj.state == "one":
                audit_record = obj.officialdocumentsauditrecord_set.filter(node='one', state='unaudit', audit_people=request.user).first()
                if approve == "audit":
                    leader_prople = request.POST.get("leader_prople", '')
                    AuditPeople = User.objects.get(id=int(leader_prople))
                    OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, state="unaudit", audit_people=AuditPeople, node="two")
                    obj.current_audit_users.add(AuditPeople)
                    obj.leaders = AuditPeople
                    obj.state = "two"
                else:
                    obj.state = "eight"
                    obj.type = "f"
                    obj.current_audit_users.add(obj.apply_user)

            elif obj.state == "two":
                audit_record = obj.officialdocumentsauditrecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
                if approve == "audit":
                    Distributors = request.POST.get("Distributors", '')             # 分发人员
                    increase_level = request.POST.get("increase_Level", '')         # 是否提升审批等级
                    LeaderList = request.POST.get("LeaderList", '')                      # 阅示领导
                    distributors_list = re.findall('\((.*?)\)', Distributors)
                    obj.increase_Level = increase_level
                    for i in distributors_list:
                        AuditPeople = User.objects.get(job_number=i)
                        if not OfficialDocumentsAuditRecord.objects.filter(official_documents_id=obj, state="unaudit", audit_people=AuditPeople, node="three").count():
                            OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, state="unaudit", audit_people=AuditPeople, node="three")
                            obj.current_audit_users.add(AuditPeople)

                    if increase_level == '2':
                        two_already_step = []
                        all_two_step = obj.officialdocumentsauditrecord_set.filter(node='two')
                        for two_step in all_two_step:
                            if two_step.audit_people not in two_already_step:
                                    OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, state="unaudit", audit_people=two_step.audit_people, node="four")

                    obj.state = "three"
                    items = []
                    try:
                        leader_list = json.loads(LeaderList)
                    except:
                        leader_list = LeaderList
                    leader_list_objs = User.objects.filter(job_number__in=leader_list, is_delete="0")
                    for leader_list_obj in leader_list_objs:
                        off_obj = OfficialDocumentsPeople(notice_id=obj, state='accept', audit_people=leader_list_obj)
                        items.append(off_obj)
                    OfficialDocumentsPeople.objects.bulk_create(items)
                else:
                    obj.state = "eight"
                    obj.type = "f"
                    obj.current_audit_users.add(obj.apply_user)

            elif obj.state == "three":
                if obj.increase_Level == '1':
                    returnData = {'code': 400, 'message': '审核等级已提升，请发起以提升请！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                audit_record = obj.officialdocumentsauditrecord_set.get(node='three', state='unaudit', audit_people=request.user)
                if approve == "audit":
                    audit_record.state = approve
                    audit_record.save()
                    Receipt = request.POST.get("Receipt", '')
                    audit_record.img_path = Receipt
                    obj.state = "four"
                    all_four_step = obj.officialdocumentsauditrecord_set.filter(node='four')
                    for four_step in all_four_step:
                        obj.current_audit_users.add(four_step.audit_people)
                else:
                    obj.current_audit_users.clear()
                    obj.state = "eight"
                    obj.type = "f"
                    obj.current_audit_users.add(obj.apply_user)

            else:
                obj.current_audit_users.clear()
                audit_record = obj.officialdocumentsauditrecord_set.get(node='four', state='unaudit', audit_people=request.user)
                if approve == "audit":
                    obj.state = "six"
                    obj.type = "e"
                else:
                    obj.state = "eight"
                    obj.current_audit_users.add(obj.apply_user)

            audit_record.update_time = datetime.datetime.now()
            audit_record.state = approve
            audit_record.audit_note = opinion_detail
            audit_record.save()
            obj.save()

        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "上级来文"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.title[:15] + "……" if len(obj.title) > 15 else obj.title
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class revoke_approval(View):
    def post(self, request):
        flow_id = request.POST.get("id", '')
        obj = OfficialDocuments.objects.get(id=int(flow_id))
        if obj.state == "one" or obj.state == "six" or obj.state == "two":
            returnData = {'code': 400, 'message': '该节点无法撤回审批！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        elif obj.state == "three":
            if obj.officialdocumentsauditrecord_set.filter(~Q(state='unaudit'), audit_people=request.user).last().node == "two":
                record_obj = obj.officialdocumentsauditrecord_set.filter(node='two', audit_people=request.user).last()
                record_obj.state = "unaudit"
                record_obj.audit_note = ""
                record_obj.save()
                obj.current_audit_users.clear()
                obj.current_audit_users.add(record_obj.audit_people)
                obj.state = "two"
                obj.save()
                obj.officialdocumentsauditrecord_set.filter(node='three').delete()
                obj.officialdocumentsauditrecord_set.filter(node='four').delete()
                obj.officialdocumentsauditrecord_set.filter(node='five').delete()
                obj.officialdocumentspeople_set.all().delete()
            else:
                Topicsattachments.objects.filter(file_type="1", uploader_user=request.user).delete()
                record_obj = obj.officialdocumentsauditrecord_set.filter(audit_people=request.user).last()
                record_obj.state = "unaudit"
                record_obj.audit_note = ""
                record_obj.save()
                obj.current_audit_users.add(record_obj.audit_people)
                obj.save()
            returnData = {'code': 200, 'message': '撤回成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        elif obj.state == "four":
            Topicsattachments.objects.filter(file_type="1", uploader_user=request.user).delete()
            record_obj = obj.officialdocumentsauditrecord_set.filter(node='three', audit_people=request.user).last()
            record_obj.state = "unaudit"
            record_obj.audit_note = ""
            record_obj.save()
            obj.current_audit_users.clear()
            obj.current_audit_users.add(record_obj.audit_people)
            obj.state = "three"
            obj.save()
            returnData = {'code': 200, 'message': '撤回成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            record_obj = obj.officialdocumentsauditrecord_set.filter(node='four', audit_people=request.user).last()
            record_obj.state = "unaudit"
            record_obj.audit_note = ""
            record_obj.save()
            obj.current_audit_users.clear()
            obj.current_audit_users.add(record_obj.audit_people)
            obj.state = "four"
            obj.save()
            returnData = {'code': 200, 'message': '撤回成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")


class external_correspondence_superiors(View):
    def post(self, request):
        flow_id = request.POST.get("id", '')
        opinion_detail = request.POST.get("opinion_detail", '')
        approve = request.POST.get("approve", '')

        obj = Correspondence.objects.get(id=int(flow_id))
        obj.audit_users_already.add(request.user)
        if obj.state == "one":
            obj.current_audit_users.clear()
            audit_record = obj.correspondencerecord_set.filter(node='one', state='unaudit').first()
            if approve == "audit":
                leader_prople = request.POST.get("leader_prople", '')
                AuditPeople = User.objects.get(id=int(leader_prople))
                CorrespondenceRecord.objects.create(official_documents_id=obj, state="unaudit", audit_people=AuditPeople, node="two")
                obj.current_audit_users.add(AuditPeople)
                obj.leaders = AuditPeople
                obj.state = "two"
            else:
                obj.state = "eight"
                obj.type = "f"
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == "two":
            obj.current_audit_users.clear()
            audit_record = obj.correspondencerecord_set.filter(node='two', state='unaudit').first()
            if approve == "audit":
                Distributors = request.POST.get("Distributors", '')
                distributors_list = re.findall('\((.*?)\)', Distributors)
                ReadingPersonnel = request.POST.get("ReadingPersonnel", '')
                for i in distributors_list:
                    AuditPeople = User.objects.get(job_number=i)
                    CorrespondenceRecord.objects.create(official_documents_id=obj, state="unaudit", audit_people=AuditPeople, node="three")
                    obj.current_audit_users.add(AuditPeople)
                CorrespondenceRecord.objects.create(official_documents_id=obj, state="unaudit", audit_people=obj.leaders, node="four")
                two_step = Company.objects.get(id=3).head_people if obj.apply_user.company.id == 3 else Company.objects.get(id=80).head_people
                CorrespondenceRecord.objects.create(official_documents_id=obj, state="unaudit", audit_people=two_step, node="five")
                obj.state = "three"

                items = []
                receive_people = re.findall('\((.*?)\)', ReadingPersonnel)
                receive_people_objs = User.objects.filter(job_number__in=receive_people, is_delete="0")
                for receive_people_obj in receive_people_objs:
                    off_obj = CorrespondencePeople(notice_id=obj, state='accept', audit_people=receive_people_obj)
                    items.append(off_obj)
                CorrespondencePeople.objects.bulk_create(items)

            else:
                obj.state = "eight"
                obj.type = "f"
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == "three":
            audit_record = obj.correspondencerecord_set.get(node='three', state='unaudit', audit_people=request.user)
            if approve == "audit":
                obj.current_audit_users.remove(request.user)
                audit_record.state = approve
                audit_record.save()
                Receipt = request.POST.get("Receipt", '')
                audit_record.img_path = Receipt
                if obj.correspondencerecord_set.filter(node='three', state='unaudit').count():
                    obj.state = "three"
                else:
                    obj.type = "a"
                    obj.state = "four"
                    obj.current_audit_users.add(obj.leaders)
            else:
                obj.current_audit_users.clear()
                obj.state = "eight"
                obj.type = "f"
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == "four":
            obj.current_audit_users.clear()
            audit_record = obj.correspondencerecord_set.get(node='four', state='unaudit', audit_people=request.user)
            if approve == "audit":
                obj.state = "five"
                obj.current_audit_users.add(Company.objects.get(id=80).head_people)
            else:
                obj.state = "three"
                obj.type = "f"
                set_list = []
                three_step = obj.correspondencerecord_set.filter(node='three')
                for step in three_step:
                    if step.audit_people not in set_list:
                        CorrespondenceRecord.objects.create(official_documents_id=obj, state="unaudit", audit_people=step.audit_people, node="three")
                        obj.current_audit_users.add(step.audit_people)
                CorrespondenceRecord.objects.create(official_documents_id=obj, state="unaudit", audit_people=obj.leaders, node="four")

        else:
            obj.current_audit_users.clear()
            audit_record = obj.correspondencerecord_set.get(node='five', state='unaudit', audit_people=request.user)
            if approve == "audit":
                obj.state = "six"
                obj.type = "e"
            else:
                obj.state = "eight"
                obj.current_audit_users.add(obj.apply_user)

        audit_record.update_time = datetime.datetime.now()
        audit_record.state = approve
        audit_record.audit_note = opinion_detail
        audit_record.save()
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "外部来函"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.title[:15] + "……" if len(obj.title) > 15 else obj.title
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class superiors_approval(View):
    def post(self, request):
        flow_id = request.POST.get("id", '')
        obj = Correspondence.objects.get(id=int(flow_id))
        if obj.state == "one" or obj.state == "six" or obj.state == "two":
            returnData = {'code': 400, 'message': '该节点无法撤回审批！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        elif obj.state == "three":
            if obj.correspondencerecord_set.filter(~Q(state='unaudit'), audit_people=request.user).last().node == "two":
                record_obj = obj.correspondencerecord_set.filter(node='two', audit_people=request.user).last()
                record_obj.state = "unaudit"
                record_obj.audit_note = ""
                record_obj.save()
                obj.current_audit_users.clear()
                obj.current_audit_users.add(record_obj.audit_people)
                obj.state = "two"
                obj.save()
                obj.correspondencerecord_set.filter(node='three').delete()
                obj.correspondencerecord_set.filter(node='four').delete()
                obj.correspondencerecord_set.filter(node='five').delete()
                obj.correspondencepeople_set.all().delete()
            else:
                Topicsattachments.objects.filter(file_type="1", uploader_user=request.user).delete()
                record_obj = obj.correspondencerecord_set.filter(audit_people=request.user).last()
                record_obj.state = "unaudit"
                record_obj.audit_note = ""
                record_obj.save()
                obj.current_audit_users.add(record_obj.audit_people)
                obj.save()
            returnData = {'code': 200, 'message': '撤回成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        elif obj.state == "four":
            Topicsattachments.objects.filter(file_type="1", uploader_user=request.user).delete()
            record_obj = obj.correspondencerecord_set.filter(node='three', audit_people=request.user).last()
            record_obj.state = "unaudit"
            record_obj.audit_note = ""
            record_obj.save()
            obj.current_audit_users.clear()
            obj.current_audit_users.add(record_obj.audit_people)
            obj.state = "three"
            obj.save()
            returnData = {'code': 200, 'message': '撤回成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            record_obj = obj.correspondencerecord_set.filter(node='four', audit_people=request.user).last()
            record_obj.state = "unaudit"
            record_obj.audit_note = ""
            record_obj.save()
            obj.current_audit_users.clear()
            obj.current_audit_users.add(record_obj.audit_people)
            obj.state = "four"
            obj.save()
            returnData = {'code': 200, 'message': '撤回成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")


class superiors_stop(View):
    def post(self, request):
        flow_id = request.POST.get("id", '')
        obj = Correspondence.objects.get(id=int(flow_id))
        obj.state = 'stop'
        obj.type = 'stop'
        obj.current_audit_users.clear()
        obj.save()
        returnData = {'code': 500, 'message': '终止失败，只有未审批完毕的流程才能种植！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class zero_refer(View):
    def post(self, request):
        flow_id = request.POST.get("id", '')
        obj = PaymentApproval.objects.get(id=int(flow_id))
        obj.current_audit_users.clear()
        obj.paymentapprovalrecord_set.filter(state='unaudit').delete()

        PaymentApprovalRecord.objects.create(official_documents_id=obj, audit_people=Company.objects.get(id=23).head_people, node="three")
        PaymentApprovalRecord.objects.create(official_documents_id=obj, audit_people=Staffing.objects.get(station="总会计师").post_personnel.all().first(), node="four")
        if obj.topics_id.pay_type == '8':
            PaymentApprovalRecord.objects.create(node='five', audit_note='', audit_people=Staffing.objects.get(station="工会经费支付").post_personnel.all().first(), official_documents_id=obj)
        else:
            PaymentApprovalRecord.objects.create(node='five', audit_note='', audit_people=Staffing.objects.get(station="财务支付").post_personnel.all().first(), official_documents_id=obj)
        obj.state = "three"
        obj.current_audit_users.add(Company.objects.get(id=23).head_people)
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "付款流程"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.title[:15] + "……" if len(obj.title) > 15 else obj.title
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '提交成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class CountersignatureModification(View):
    def post(self, request):
        flow_id = request.POST.get("id", '')
        contract_obj = ContractApproval.objects.get(id=int(flow_id))
        contract_obj.current_audit_users.clear()
        contract_obj.contractapprovalrecord_set.filter(state='unaudit').delete()
        if contract_obj.contractapprovalrecord_set.filter(node="negative"):
            negative_obj = contract_obj.contractapprovalrecord_set.filter(node="negative").first()
            ContractApprovalRecord.objects.create(official_documents_id=contract_obj, audit_people=negative_obj.audit_people, node="negative")
            ContractApprovalRecord.objects.create(official_documents_id=contract_obj, audit_people=negative_obj.audit_people.company.leaders_id, node="zero")
            contract_obj.state = "negative"
            contract_obj.current_audit_users.add(negative_obj.audit_people)
        elif contract_obj.contractapprovalrecord_set.filter(node="six"):
            ContractApprovalRecord.objects.create(official_documents_id=contract_obj, audit_people=contract_obj.apply_user, node="six")
            ContractApprovalRecord.objects.create(official_documents_id=contract_obj, audit_people=contract_obj.apply_user.company.leaders_id, node="zero")
            contract_obj.state = "six"
            contract_obj.current_audit_users.add(contract_obj.apply_user)
        else:
            contract_obj.state = "one"
            contract_obj.current_audit_users.add(Company.objects.get(id=22).head_people)
        ContractApprovalRecord.objects.create(official_documents_id=contract_obj, audit_people=Company.objects.get(id=22).head_people, node="one")
        ContractApprovalRecord.objects.create(official_documents_id=contract_obj, audit_people=Company.objects.get(id=23).head_people, node="two")
        ContractApprovalRecord.objects.create(official_documents_id=contract_obj, audit_people=Company.objects.get(id=18).head_people, node="three")
        ContractApprovalRecord.objects.create(official_documents_id=contract_obj, audit_people=Staffing.objects.get(station="院长").post_personnel.all().first(), node="four")
        ContractApprovalRecord.objects.create(official_documents_id=contract_obj, audit_people=Staffing.objects.get(station="印章管理员").post_personnel.all().first(), node="five")
        contract_obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "付款流程"
        applicant = contract_obj.apply_user.real_name
        ApplicationTime = contract_obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = contract_obj.title[:15] + "……" if len(contract_obj.title) > 15 else contract_obj.title
        for jj in contract_obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '提交成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class TopicScanCode(View):
    def post(self, request):
        user_id = request.POST.get("user_id", '')
        ScanObj = ScanCode.objects.filter(type="1", whether_scan='0')
        topic_obj = topic_meeting.objects.filter(topic_year=str(ScanObj.meet_year), meet_number=str(ScanObj.meet_number), topic_type='yb')

        code_scanner = User.objects.get(id=int(user_id))
        for top_obj in topic_obj:
            top_obj.state = 'voting'
            top_obj.save()
            if top_obj.compere == code_scanner:
                host_flag = True
            else:
                host_flag = False
            VoteLeader.objects.create(leaders=code_scanner, topics_id=top_obj, meet_number=ScanObj.meet_number, topic_year=ScanObj.meet_year, vote=True, Participation=True, host=host_flag, reason='')
        returnData = {'code': 200, 'message': '扫码成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class MeetingRoomScanCodeConfirmation(LoginRequiredMixin, View):
    def get(self, request):
        flow_id = request.GET.get("flow_id", '')
        timestamp = request.GET.get("timestamp", '')
        flow_type = request.GET.get("type", '')
        js_code = request.GET.get("js_code", '')

        # 获取微信OPENID
        headers = {"Accept": "application/json", }
        get_url = f"https://api.weixin.qq.com/sns/jscode2session?appid=wxc669281d321d4ed1&secret=371945c837b88a952c1883b7c11b3ead&js_code={js_code}&grant_type=authorization_code"
        reql = requests.get(get_url, headers=headers)
        openid = reql.json()["openid"]

        if str(flow_type) == "1":
            obj = ConferenceRoomApplication.objects.get(id=int(flow_id))
            if obj.conferenceroomsignee_set.filter(uid=openid):
                returnDict = {'code': 400, 'message': "该设备本次会议已扫码，无法重复扫码！"}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            if obj.conferenceroomsignee_set.filter(SigneeCode=request.user, scan_or_not='1'):
                returnDict = {'code': 400, 'message': "已扫码，无需重复扫码！"}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
        # now_time = time.time()
        # time_difference = now_time - int(timestamp)/1000
        # if time_difference > 15:
        #     returnDict = {'code': 400, 'message': "签到码已过期！"}
        # else:
        returnDict = {'code': 200, 'message': 'success', 'url': "/new-flow-logic/MeetingRoomCheckIn", "method": "post", "real_name": request.user.real_name, "job_number": request.user.job_number, "user_id": request.user.id, "flow_id": flow_id, "uid": openid}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class meeting_room_check_in(LoginRequiredMixin, View):
    def post(self, request):
        user_id = request.POST.get("user_id", '')
        flow_id = request.POST.get("flow_id", '')
        uid = request.POST.get("uid", '')
        obj = ConferenceRoomApplication.objects.get(id=int(flow_id))
        code_scanner = User.objects.get(job_number=user_id)
        if ConferenceRoomSignee.objects.filter(parent_id=obj, SigneeCode=code_scanner):
            sing_obj = ConferenceRoomSignee.objects.get(parent_id=obj, SigneeCode=code_scanner)
            sing_obj.update_time = datetime.datetime.now()
            sing_obj.scan_or_not = "1"
            sing_obj.uid = uid
            sing_obj.save()
            print("==========================更改的ID是：", sing_obj.id, sing_obj.scan_or_not)
        else:
            ConferenceRoomSignee.objects.create(parent_id=obj, SigneeCode=code_scanner, uid=uid, scan_or_not="1")
        returnData = {'code': 200, 'message': '扫码成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class meeting_room_check_detail(View):
    def post(self, request):
        flow_id = request.POST.get("id", '')
        obj = ConferenceRoomApplication.objects.get(id=int(flow_id))
        dteail_obj = obj.conferenceroomsignee_set.all()
        alread_list = []
        no_list = []
        leave_list = []
        for i in dteail_obj:
            if i.leave == '0':
                if i.scan_or_not == "1":
                    alread_list.append({"name": i.SigneeCode.real_name, "time": i.update_time.strftime("%Y-%m-%d %H:%M"), 'id': i.SigneeCode.id, 'flow_id': flow_id})
                else:
                    no_list.append({"name": i.SigneeCode.real_name, "time": i.update_time.strftime("%Y-%m-%d %H:%M"), 'id': i.SigneeCode.id, 'flow_id': flow_id})
            else:
                leave_list.append({"name": i.SigneeCode.real_name, "time": i.update_time.strftime("%Y-%m-%d %H:%M"), 'id': i.SigneeCode.id, 'flow_id': flow_id})
        returnData = {'code': 200, 'message': '扫码成功！', "alread_list": alread_list, "no_list": no_list, 'leave_list': leave_list}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class AskForLeave(View):
    def post(self, request):
        person_id = request.POST.get("person_id", '')
        flow_id = request.POST.get("flow_id", '')
        try:
            obj = ConferenceRoomApplication.objects.get(id=int(flow_id))
            signee_code = User.objects.get(id=int(person_id))
            dteail_obj = obj.conferenceroomsignee_set.filter(SigneeCode=signee_code).first()
            dteail_obj.leave = 1
            dteail_obj.save()
            returnData = {'code': 200, 'message': '操作成功！', 'data': []}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        except:
            returnData = {'code': 400, 'message': '操作失败！请查看请假人员是否在人员名单中！', 'data': []}
            return HttpResponse(json.dumps(returnData), content_type="application/json")


class TopicScanCodeConfirmation(LoginRequiredMixin, View):
    def get(self, request):
        timestamp = request.GET.get("timestamp", '')
        topic_year = request.GET.get("topic_year", '')
        meet_number = request.GET.get("meet_number", '')
        topic_type = request.GET.get("type", '')
        js_code = request.GET.get("js_code", '')

        headers = {"Accept": "application/json", }
        get_url = f"https://api.weixin.qq.com/sns/jscode2session?appid=wxc669281d321d4ed1&secret=371945c837b88a952c1883b7c11b3ead&js_code={js_code}&grant_type=authorization_code"
        reql = requests.get(get_url, headers=headers)

        openid = reql.json()["openid"]

        obj = topic_sing.objects.filter(meet_number=meet_number, topic_type=topic_type, topic_year=topic_year, uid=openid)
        if obj.count():
            returnDict = {'code': 400, 'message': "该设备本次会议已扫码，无法重复扫码！"}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        if topic_sing.objects.filter(meet_number=meet_number, topic_type=topic_type, topic_year=topic_year, uid=openid, leaders=request.user):
            returnDict = {'code': 400, 'message': "已扫码，无需重复扫码！"}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        now_time = time.time()
        time_difference = now_time - int(timestamp)/1000
        print("======================", time_difference)
        # if time_difference > 15:
        #     returnDict = {'code': 400, 'message': "签到码已过期！"}
        # else:
        returnDict = {'code': 200, 'message': 'success', 'url': "/new-flow-logic/topic_checkIn", "method": "post", "real_name": request.user.real_name,
                          "job_number": request.user.job_number, "user_id": request.user.id, "meet_number": meet_number, "uid": openid, "topic_type": topic_type, "topic_year": topic_year}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class TopicCheckIn(LoginRequiredMixin, View):
    def post(self, request):
        user_id = request.POST.get("user_id", '')
        meet_number = request.POST.get("meet_number", '')
        topic_type = request.POST.get("topic_type", '')
        topic_year = request.POST.get("topic_year", '')
        uid = request.POST.get("uid", '')
        print("===================", topic_year, meet_number, topic_type)
        topic_obj = topic_meeting.objects.filter(topic_year=str(topic_year), meet_number=str(meet_number), topic_type=topic_type.strip())

        CheckPeople = User.objects.get(job_number=int(user_id))
        if topic_type == 'yb':
            meet_obj = Staffing.objects.get(station='院办议题投票').post_personnel.all()
        else:
            meet_obj = Staffing.objects.get(station='党委议题投票').post_personnel.all()
        if CheckPeople in meet_obj:
            for top_obj in topic_obj:

                if top_obj.compere == CheckPeople:
                    host = True
                else:
                    host = False
                VoteLeader.objects.create(leaders=CheckPeople, topics_id=top_obj, meet_number=meet_number, topic_year=topic_year, vote=True, Participation=True, host=host)

        topic_sing.objects.create(leaders=CheckPeople, sing_time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M"), meet_number=meet_number, topic_type=topic_type,
                                  topic_year=topic_year, sing_type="1", uid=uid)

        returnData = {'code': 200, 'message': '扫码成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class SignDetail(LoginRequiredMixin, View):
    def post(self, request):
        meet_number = request.POST.get("meet_number", '')
        topic_type = request.POST.get("topic_type", '')
        topic_year = request.POST.get("topic_year", '')
        leave_obj = topic_sing.objects.filter(meet_number=meet_number, topic_type=topic_type, topic_year=topic_year, sing_type="2")
        sing_obj = topic_sing.objects.filter(meet_number=meet_number, topic_type=topic_type, topic_year=topic_year, sing_type="1")
        leave_dict = []
        sing_dict = []
        for i in leave_obj:
            leave_dict.append({"real_name": i.leaders.real_name, "time": i.create_time.strftime("%Y-%m-%d %H:%M")})

        for j in sing_obj:
            sing_dict.append({"real_name": j.leaders.real_name, "time": j.create_time.strftime("%Y-%m-%d %H:%M")})

        returnData = {'code': 200, 'message': '获取成功！', "leave_dict": leave_dict, "sing_dict": sing_dict}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class CommitteeAttendanceTable(LoginRequiredMixin, View):
    def get(self, request):
        timestamp = request.GET.get("timestamp", '')
        meeting_name = request.GET.get("meeting_name", '')
        meet_number = request.GET.get("meet_number", '')
        js_code = request.GET.get("js_code", '')

        headers = {"Accept": "application/json", }
        get_url = f"https://api.weixin.qq.com/sns/jscode2session?appid=wxc669281d321d4ed1&secret=371945c837b88a952c1883b7c11b3ead&js_code={js_code}&grant_type=authorization_code"
        reql = requests.get(get_url, headers=headers)

        openid = reql.json()["openid"]

        obj = CommitteeAttendance.objects.filter(committee_name__committee_name=meeting_name, number=meet_number, uid=openid)
        if obj.count():
            returnDict = {'code': 400, 'message': "该设备本次会议已扫码，无法重复扫码！"}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        now_time = time.time()
        time_difference = now_time - int(timestamp)/1000
        returnDict = {'code': 200, 'message': 'success', 'url': "/new-flow-logic/committee_attendance_checkIn", "method": "post", "real_name": request.user.real_name,
                          "job_number": request.user.job_number, "user_id": request.user.id, "meet_number": meet_number, "uid": openid, "meeting_name": meeting_name}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class CommitteeAttendanceCheckIn(LoginRequiredMixin, View):
    def post(self, request):
        user_id = request.POST.get("user_id", '')
        meet_number = request.POST.get("meet_number", '')
        meeting_name = request.POST.get("meeting_name", '')
        uid = request.POST.get("uid", '')

        committee_obj = CommitteeTable.objects.get(committee_name=meeting_name)                             # 委员会名称
        topic_obj = AttendedMeeting.objects.filter(committee_name=committee_obj, number=meet_number)        # 投票议题列表

        CheckPeople = User.objects.get(job_number=int(user_id)).real_name           # 扫码人
        expert_obj = topic_obj.first().topic.expert_database.expertpeople_set.all() if topic_obj.first().topic.expert_database else []
        expert_list = [i.name for i in expert_obj]
        if expert_list:
            if CheckPeople in expert_list:
                for top_obj in topic_obj:
                    if top_obj.compere.real_name == CheckPeople:
                        host = True
                    else:
                        host = False
                    AttendedMeetingPeople.objects.create(leaders=CheckPeople, topics_id=top_obj, host=host)
        else:
            for top_obj in topic_obj:
                if top_obj.compere.real_name == CheckPeople:
                    host = True
                else:
                    host = False
                AttendedMeetingPeople.objects.create(leaders=CheckPeople, topics_id=top_obj, host=host)

        bbb_obj = CommitteeAttendance.objects.filter(committee_name__committee_name=meeting_name, number=meet_number, signee=CheckPeople)
        if bbb_obj.count():
            bbb_obj.first().sing = "1"
            bbb_obj.first().uid = uid
            bbb_obj.first().save()
        else:
            CommitteeAttendance.objects.create(committee_name=committee_obj, number=meet_number, signee=CheckPeople, sing="1", uid=uid)

        returnData = {'code': 200, 'message': '扫码成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class CommitteeAttendanceSignDetail(View):
    def post(self, request):
        meet_number = request.POST.get("meet_number", '')
        meeting_name = request.POST.get("meeting_name", '')
        print(meet_number, meeting_name)
        leave_obj = CommitteeAttendance.objects.filter(number=meet_number, committee_name__committee_name=meeting_name, sing="0")
        sing_obj = CommitteeAttendance.objects.filter(number=meet_number, committee_name__committee_name=meeting_name, sing="1")
        leave_dict = []
        sing_dict = []
        for i in leave_obj:
            leave_dict.append({"real_name": i.signee, "time": i.update_time.strftime("%Y-%m-%d %H:%M")})

        for j in sing_obj:
            sing_dict.append({"real_name": j.signee, "time": j.update_time.strftime("%Y-%m-%d %H:%M")})
        returnData = {'code': 200, 'message': '获取成功！', "leave_dict": leave_dict, "sing_dict": sing_dict}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class MeetingLeaveList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, "NewFlowLogic/meetingleavelist.html", {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        objs = MeetingRoomLeave.objects.filter(apply_user=request.user).order_by('-create_time')
        data_list = [{'id': obj.id,
                      'particulars': obj.meet_main.particulars if obj.meet_main else "",
                      'names': obj.meet_main.names if obj.meet_main else "", 'state': obj.get_state_str(),
                      'meeting_root': obj.meet_main.meeting_root if obj.meet_main else "", 'reason': obj.reason,
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": f"<a href='meetingleavedraft.html?id={obj.id}'>编辑</a> | <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == 'draft'
                      else f"<a href='meetingleavedetail.html?id={obj.id}'>查看</a> | <a href='meetingleavedetail.html?revise=true&id={obj.id}'>修改</a>" if obj.can_revise == '1' and obj.state != 'draft'
                      else f"<a href='meetingleavedetail.html?id={obj.id}'>查看</a> |  <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == "stop" else f"<a href='meetingleavedetail.html?id={obj.id}'>查看</a>",
                      }
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class MeetingLeaveIndex(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        MeetRoomObj = ConferenceRoomSignee.objects.filter(SigneeCode=request.user, parent_id__status__in=['0', '1'])
        return render(request, "NewFlowLogic/meetingleaveindex.html", {'realname': real_name, 'position': position, 'department': department, 'MeetRoomObj': MeetRoomObj})

    def post(self, request):
        flow_id = request.POST.get("flow_id", '')
        reason = request.POST.get("reason", '')  # 修改原因
        note = request.POST.get("note", '')
        leave_meeting = request.POST.get("leave_meeting", '')

        if flow_id:
            obj = MeetingRoomLeave.objects.get(id=int(flow_id))
            obj.reason = reason
            obj.note = note
            obj.meet_main = ConferenceRoomApplication.objects.get(id=int(leave_meeting))
            obj.meetingroomleaverecord_set.filter(state='unaudit').delete()
            obj.current_audit_users.clear()
        else:
            obj = MeetingRoomLeave.objects.create(apply_user=request.user, reason=reason, meet_main = ConferenceRoomApplication.objects.get(id=int(leave_meeting)),
                                                  note=note, company=request.user.company)

        one_flag = True
        one_step = request.user.company.head_people
        if request.user != one_step:
            MeetingRoomLeaveRecord.objects.create(parent_id=obj, audit_people=one_step, state='unaudit', audit_note='', node='one')
            obj.state = 'one'
            obj.current_audit_users.add(one_step)
            one_flag = False

        two_flag = True
        if not request.user.company.is_functional:
            if '护士' in request.user.role or '护理' in request.user.role:
                two_step = Company.objects.get(id=15).head_people
            else:
                two_step = Company.objects.get(id=13).head_people
            MeetingRoomLeaveRecord.objects.create(parent_id=obj, audit_people=two_step, state='unaudit', audit_note='', node='two')
            if one_flag:
                obj.state = 'two'
                obj.current_audit_users.add(two_step)
                two_flag = False

        MeetingRoomLeaveRecord.objects.create(parent_id=obj, audit_people=request.user.company.leaders_id, state='unaudit', audit_note='', node='three')
        if one_flag and two_flag:
            obj.state = 'three'
            obj.current_audit_users.add(request.user.company.leaders_id)
        if obj.meet_main.apply_user:
            MeetingRoomLeaveRecord.objects.create(parent_id=obj, audit_people=obj.meet_main.apply_user, state='unaudit', audit_note='', node='four')
        else:
            MeetingRoomLeaveRecord.objects.create(parent_id=obj, audit_people=User.objects.filter(real_name=obj.meet_main.names, department=obj.meet_main.department).first(), state='unaudit', audit_note='', node='four')

        obj.save()
        returnDict = {'code': 200, 'message': "保存成功！"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class MeetingLeaveDraft(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        flow_id = request.GET.get('id', None)
        obj = MeetingRoomLeave.objects.get(id=int(flow_id))
        MeetRoomObj = ConferenceRoomSignee.objects.filter(SigneeCode=request.user, parent_id__status__in=['0', '1'])
        return render(request, "NewFlowLogic/meetingleavedraft.html", {'realname': real_name, 'position': position, 'department': department, 'obj': obj, 'MeetRoomObj': MeetRoomObj})

    def post(self, request):
        flow_id = request.POST.get("flow_id", '')
        reason = request.POST.get("reason", '')  # 修改原因
        note = request.POST.get("note", '')
        leave_meeting = request.POST.get("leave_meeting", '')

        if flow_id:
            obj = MeetingRoomLeave.objects.get(id=int(flow_id))
            obj.reason = reason
            obj.note = note
            if leave_meeting != '0':
                obj.meet_main = ConferenceRoomApplication.objects.get(id=int(leave_meeting))
        else:
            if leave_meeting != '0':
                obj = MeetingRoomLeave.objects.create(apply_user=request.user, reason=reason, meet_main = ConferenceRoomApplication.objects.get(id=int(leave_meeting)),
                                                      note=note, company=request.user.company)
            else:
                obj = MeetingRoomLeave.objects.create(apply_user=request.user, reason=reason, note=note, company=request.user.company)
        obj.state = "draft"
        obj.save()
        returnDict = {'code': 200, 'message': "保存成功！"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class MeetingLeaveDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        flow_id = request.GET.get('id', None)
        obj = MeetingRoomLeave.objects.get(id=int(flow_id))

        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.meetingroomleaverecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append(
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime(
                        "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (
                                 audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.meetingroomleaverecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime(
                        "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (
                                 audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        MeetRoomObj = ConferenceRoomSignee.objects.filter(SigneeCode=request.user, parent_id__status__in=['0', '1'])
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, "audit_dic": audit_dic, "flow_dict": flow_dict, 'MeetRoomObj': MeetRoomObj,
                   'is_edit': 'true' if obj.state == 'refuse' and obj.apply_user == request.user else 'false',
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'refuse'] and request.user == obj.apply_user else 'false'
                   }
        return render(request, "NewFlowLogic/meetingleavedetail.html", context)

    def post(self, request):
        flow_id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "会议请假")
        except:
            pass
        obj = MeetingRoomLeave.objects.get(id=int(flow_id))
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.meetingroomleaverecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                if obj.meetingroomleaverecord_set.filter(node='two'):
                    next_audit_record = obj.meetingroomleaverecord_set.filter(node='two', state='unaudit').first()
                    obj_state = 'two'
                elif obj.meetingroomleaverecord_set.filter(node='three'):
                    next_audit_record = obj.meetingroomleaverecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
                else:
                    next_audit_record = obj.meetingroomleaverecord_set.filter(node='four', state='unaudit').first()
                    obj_state = 'four'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.meetingroomleaverecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                if obj.meetingroomleaverecord_set.filter(node='three'):
                    next_audit_record = obj.meetingroomleaverecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
                else:
                    next_audit_record = obj.meetingroomleaverecord_set.filter(node='four', state='unaudit').first()
                    obj_state = 'four'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.meetingroomleaverecord_set.filter(node='three', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_record = obj.meetingroomleaverecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            audit_record = obj.meetingroomleaverecord_set.filter(node='four', state='unaudit').first()
            if state == 'audit':
                obj_state = 'end'
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()

        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class MeetingLeaveStop(View):
    def post(self, request):
        id = request.POST.get('id', None)
        types = request.POST.get('types', 'stop')  # stop 终止 delete 删除
        obj = MeetingRoomLeave.objects.get(id=int(id))
        if types == 'stop':
            if obj.state == 'end':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的流程不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
                returnData = {'code': 200, 'message': '终止成功！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            obj.current_audit_users.clear()
            obj.meetingroomleaverecord_set.all().delete()
            obj.audit_users_already.clear()
            obj.delete()
            returnData = {'code': 200, 'message': '删除成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

# 查询已完结差旅申请数据
class SearchTravelApplications(View):
    def post(self, request):
        search_type = request.POST.get("search_type", "")
        start_time = request.POST.get("start_time", "")
        end_time = request.POST.get("end_time", "")

        if not search_type:
            returnData = {'code': 200, "status": 'err', 'message': '缺少必要参数，查询数据类别。', 'data': []}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        return_data = []
        if search_type == '1':
            if start_time and not end_time:
                start_date_object = datetime.datetime.strptime(start_time, "%Y-%m-%d")
                obj = TravelApply.objects.filter(state='five', create_time__gte=start_date_object).order_by('-create_time')
            elif end_time and not start_time:
                end_date_object = datetime.datetime.strptime(end_time, "%Y-%m-%d")
                obj = TravelApply.objects.filter(state='five', create_time__lte=end_date_object).order_by('-create_time')
            elif start_time and end_time:
                start_date_object = datetime.datetime.strptime(start_time, "%Y-%m-%d")
                end_date_object = datetime.datetime.strptime(end_time, "%Y-%m-%d")
                obj = TravelApply.objects.filter(state='five', create_time__range=[start_date_object, end_date_object]).order_by('-create_time')
            else:
                obj = TravelApply.objects.filter(state='five').order_by('-create_time')

            for i in obj:
                return_data.append({
                    "create_time": i.create_time.strftime("%Y-%m-%d %H:%M"), "travel_people": ', '.join([j.real_name for j in i.travel_users.all()]),
                    "travel_type": "学术会议出差" if i.travel_type == 'one' else '进修出差' if i.travel_type == 'two' else '行政出差' if i.travel_type == 'three' else "其他",
                    "start_time": i.start_time.split(" ")[0], "end_time": i.end_time.split(" ")[0], "subject": i.subject, "route": i.route
                })
        else:
            if start_time and not end_time:
                start_date_object = datetime.datetime.strptime(start_time, "%Y-%m-%d")
                obj = LeaveRequest.objects.filter(state="seven", create_time__gte=start_date_object).order_by('-create_time')
            elif end_time and not start_time:
                end_date_object = datetime.datetime.strptime(end_time, "%Y-%m-%d")
                obj = LeaveRequest.objects.filter(state="seven", create_time__lte=end_date_object).order_by('-create_time')
            elif start_time and end_time:
                start_date_object = datetime.datetime.strptime(start_time, "%Y-%m-%d")
                end_date_object = datetime.datetime.strptime(end_time, "%Y-%m-%d")
                obj = LeaveRequest.objects.filter(state="seven", create_time__range=[start_date_object, end_date_object]).order_by('-create_time')
            else:
                obj = LeaveRequest.objects.filter(state="seven").order_by('-create_time')

            for k in obj:
                return_data.append({
                    "create_time": k.create_time.strftime("%Y-%m-%d %H:%M"), "apply_user": k.apply_user.real_name, "company": k.company.name, "leave_type": k.get_leave_type(),
                    "job_num": k.job_num, "reason": k.reason, "start_time": k.start_time.split(" ")[0], "end_time": k.end_time.split(" ")[0], "days": k.days
                })
        returnData = {'code': 200, "status": 'success', 'message': '', 'data': return_data}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class AttendanceInterfaceView(View):
    def post(self, request):
        try:
            # request_data = json.loads(request.body)
            AttendanceInformation.objects.create(request_data=json.loads(request.body))
            # for i in request_data["recoLogList"]:
            #     CheckInInformation.objects.create()
        except Exception as E:
            returnData = {'code': 500, "status": 'success', 'message': str(E)}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        returnData = {'code': 200, "status": 'success', 'message': ''}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class ThreeBestScheduling(View):
    def post(self, request):
        department = request.POST.get("department", "")
        real_name = request.POST.get("real_name", "")
        job_number = request.POST.get("job_number", "")
        duty_date = request.POST.get("duty_date", "")           # 值班日期
        start_time = request.POST.get("start_time", "")         # 开始时间
        end_time = request.POST.get("end_time", "")             # 结束时间
        start_time1 = request.POST.get("start_time1", "")  # 开始时间
        end_time1 = request.POST.get("end_time1", "")  # 结束时间
        rank = request.POST.get("rank", "")                     # 班次

        if not department:
            returnData = {'code': 400, "status": 'success', 'message': '科室不能为空'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        elif not real_name:
            returnData = {'code': 400, "status": 'success', 'message': '姓名不能为空'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        elif not job_number:
            returnData = {'code': 400, "status": 'success', 'message': '工号不能为空'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        elif not duty_date:
            returnData = {'code': 400, "status": 'success', 'message': '值班日期不能为空'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        elif not start_time:
            returnData = {'code': 400, "status": 'success', 'message': '值班开始时间不能为空'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        elif not end_time:
            returnData = {'code': 400, "status": 'success', 'message': '值班结束时间不能为空'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        elif not start_time1:
            returnData = {'code': 400, "status": 'success', 'message': '值班开始时间不能为空'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        elif not end_time1:
            returnData = {'code': 400, "status": 'success', 'message': '值班结束时间不能为空'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        elif not rank:
            returnData = {'code': 400, "status": 'success', 'message': '班次不能为空'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            ThreePartyAttendanceInformation.objects.create(real_name=real_name, department=department, job_number=job_number,
            duty_date=duty_date, start_time=start_time, end_time=end_time, start_time1=start_time1, end_time1=end_time1, rank=rank)
            returnData = {'code': 200, "status": 'success', 'message': ''}
            return HttpResponse(json.dumps(returnData), content_type="application/json")


class OfficialBusinessReceptionList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, "NewFlowLogic/official_business_reception_list.html", {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        objs = BeforehandReception.objects.filter(apply_user=request.user).order_by('-create_time')
        data_list = [{'id': obj.id, 'guest_unit_name': obj.guest_unit_name, 'reception_reason': obj.reception_reason, 'state': obj.get_state_str(),
          'reception_time': obj.reception_time, 'reception_location': obj.reception_location, 'budget': obj.budget,
          'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
          "url": f"<a href='official_business_reception_draft.html?id={obj.id}'>编辑</a> | <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == 'draft'
          else f"<a href='official_business_reception_detail.html?id={obj.id}'>查看</a> | <a href='official_business_reception_detail.html?revise=true&id={obj.id}'>修改</a>" if obj.can_revise == '1' and obj.state != 'draft'
          else f"<a href='official_business_reception_detail.html?id={obj.id}'>查看</a> |  <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == "stop" else f"<a href='official_business_reception_detail.html?id={obj.id}'>查看</a>",
          }
         for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class OfficialBusinessReceptionIndex(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        fj_number = uuid.uuid4()
        return render(request, "NewFlowLogic/official_business_reception_index.html", {'realname': real_name, 'position': position, 'department': department, "uuid": fj_number})

    def post(self, request):
        flow_id = request.POST.get("id", '')
        guest_unit_name = request.POST.get("guest_unit_name", '')
        reception_reason = request.POST.get("reception_reason", '')
        reception_time = request.POST.get("reception_time", '')
        reception_location = request.POST.get("reception_location", '')
        budget = request.POST.get("budget", '')
        reception_capacity = request.POST.get("reception_capacity", '')
        meal_expenses = request.POST.get("meal_expenses", '')
        other_expenses = request.POST.get("other_expenses", '')
        accompany_meal = request.POST.get("accompany_meal", '')
        note = request.POST.get("note", '')
        fj_number = request.POST.get("fj_number", '')

        if flow_id:
            obj = BeforehandReception.objects.get(id=int(flow_id))
            obj.guest_unit_name = guest_unit_name
            obj.note = note
            obj.reception_reason = reception_reason
            obj.reception_time = reception_time
            obj.reception_location = reception_location
            obj.budget = budget
            obj.reception_capacity = reception_capacity
            obj.meal_expenses = meal_expenses
            obj.other_expenses = other_expenses
            obj.accompany_meal = accompany_meal

            obj.beforehandreceptionrecord_set.filter(state='unaudit').delete()
            obj.current_audit_users.clear()
        else:
            obj = BeforehandReception.objects.create(apply_user=request.user, company=request.user.company, guest_unit_name=guest_unit_name, reception_reason=reception_reason,
                                                  note=note, reception_time=reception_time, reception_location=reception_location, budget=budget, reception_capacity=reception_capacity,
                                                  meal_expenses=meal_expenses, other_expenses=other_expenses, accompany_meal=accompany_meal, fj_number=fj_number)

        one_flag = True
        one_step = request.user.company.head_people
        if request.user != one_step:
            BeforehandReceptionRecord.objects.create(parent_id=obj, audit_people=one_step, state='unaudit', audit_note='', node='one')
            obj.state = 'one'
            obj.current_audit_users.add(one_step)
            one_flag = False

        two_step = request.user.company.leaders_id
        BeforehandReceptionRecord.objects.create(parent_id=obj, audit_people=two_step, state='unaudit', audit_note='', node='two')
        if one_flag:
            obj.state = 'two'
            obj.current_audit_users.add(two_step)

        three_step = Company.objects.get(id=23).head_people
        BeforehandReceptionRecord.objects.create(parent_id=obj, audit_people=three_step, state='unaudit', audit_note='', node='three')
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "公务（外宾）接待事前审批"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.reception_reason[:15] + "……" if len(obj.reception_reason) > 15 else obj.reception_reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        obj.save()
        returnDict = {'code': 200, 'message': "操作成功！"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class OfficialBusinessReceptionDraft(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        flow_id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = BeforehandReception.objects.get(id=int(flow_id))
        audit_dic, flow_dict = {}, {}
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': request.user.real_name, 'position': request.user.post, 'file_list': file_list,
                   'department': request.user.company.name, 'obj': obj, "audit_dic": audit_dic,
                   'revise': revise, "flow_dict": flow_dict, "applicat_time": datetime.datetime.now().strftime("%Y-%m-%d"),
                   "Telephone": request.user.mobile}
        return render(request, "NewFlowLogic/official_business_reception_draft.html", context)

    def post(self, request):
        flow_id = request.POST.get("id", '')
        guest_unit_name = request.POST.get("guest_unit_name", '')
        reception_reason = request.POST.get("reception_reason", '')
        reception_time = request.POST.get("reception_time", '')
        reception_location = request.POST.get("reception_location", '')
        budget = request.POST.get("budget", '')
        reception_capacity = request.POST.get("reception_capacity", '')
        meal_expenses = request.POST.get("meal_expenses", '')
        other_expenses = request.POST.get("other_expenses", '')
        accompany_meal = request.POST.get("accompany_meal", '')
        note = request.POST.get("note", '')
        fj_number = request.POST.get("fj_number", '')

        if flow_id:
            obj = BeforehandReception.objects.get(id=int(flow_id))
            obj.guest_unit_name = guest_unit_name
            obj.note = note
            obj.reception_reason = reception_reason
            obj.reception_time = reception_time
            obj.reception_location = reception_location
            obj.budget = budget
            obj.reception_capacity = reception_capacity
            obj.meal_expenses = meal_expenses
            obj.other_expenses = other_expenses
            obj.accompany_meal = accompany_meal
        else:
            obj = BeforehandReception.objects.create(apply_user=request.user, company=request.user.company, guest_unit_name=guest_unit_name, reception_reason=reception_reason,
                                                  note=note, reception_time=reception_time, reception_location=reception_location, budget=budget, reception_capacity=reception_capacity,
                                                  meal_expenses=meal_expenses, other_expenses=other_expenses, accompany_meal=accompany_meal, fj_number=fj_number)
        obj.state = "draft"
        obj.save()
        returnDict = {'code': 200, 'message': "保存成功！"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class OfficialBusinessReceptionDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        flow_id = request.GET.get('id', None)
        obj = BeforehandReception.objects.get(id=int(flow_id))

        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.beforehandreceptionrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append(
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.beforehandreceptionrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, "audit_dic": audit_dic, "flow_dict": flow_dict, "file_list": file_list,
                   'is_edit': 'true' if obj.state == 'refuse' and obj.apply_user == request.user else 'false',
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'refuse'] and request.user == obj.apply_user else 'false',
                    'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, "NewFlowLogic/official_business_reception_detail.html", context)

    def post(self, request):
        flow_id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "公务(外宾)接待事前审批")
        except:
            pass
        obj = BeforehandReception.objects.get(id=int(flow_id))
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.remove(request.user)
        if obj.state == 'one':
            audit_record = obj.beforehandreceptionrecord_set.filter(node='one', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.beforehandreceptionrecord_set.filter(node='two'):
                    next_audit_record = obj.beforehandreceptionrecord_set.filter(node='two', state='unaudit').first()
                    obj_state = 'two'
                else:
                    next_audit_record = obj.beforehandreceptionrecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.beforehandreceptionrecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_record = obj.beforehandreceptionrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.beforehandreceptionrecord_set.filter(node='three', state='unaudit').first()
            if state == 'audit':
                obj_state = 'end'
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()

        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class OfficialBusinessReceptionOperate(View):
    def post(self, request):
        operate_type = request.POST.get("operate_type", "")
        flow_id = request.POST.get("flow_id", "")

        flow_obj = BeforehandReception.objects.get(id=int(flow_id))
        flow_obj.current_audit_users.clear()
        if operate_type == 'stop':
            flow_obj.state = "stop"
            flow_obj.save()
            message = "终止成功！"
        else:
            flow_obj.audit_users_already.clear()
            flow_obj.beforehandreceptionrecord_set.all().delete()
            flow_obj.delete()
            message = "删除成功！"
        returnData = {'code': 200, "status": 'success', 'message': message}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class ReceptionChecklistList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, "NewFlowLogic/reception_checklist_list.html", {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        objs = ReceptionChecklist.objects.filter(apply_user=request.user).order_by('-create_time')
        data_list = [{'id': obj.id, 'official_interaction': obj.official_interaction, 'accompanying_personnel': ",".join([i.real_name for i in obj.accompanying_personnel.all()]),
          'state': obj.get_state_str(), 'reception_location': obj.reception_location, 'amount_to': obj.amount_to,
          'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
          "url": f"<a href='reception_checklist_draft.html?id={obj.id}'>编辑</a> | <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == 'draft'
          else f"<a href='reception_checklist_detail.html?id={obj.id}'>查看</a> | <a href='reception_checklist_detail.html?revise=true&id={obj.id}'>修改</a>" if obj.can_revise == '1' and obj.state != 'draft' and obj.state != "stop"
          else f"<a href='reception_checklist_detail.html?id={obj.id}'>查看</a> |  <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == "stop" else f"<a href='reception_checklist_detail.html?id={obj.id}'>查看</a>",
          }
         for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ReceptionChecklistIndex(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        fj_number = uuid.uuid4()
        return render(request, "NewFlowLogic/reception_checklist_index.html", {'realname': real_name, 'position': position, 'department': department, "uuid": fj_number})

    def post(self, request):
        flow_id = request.POST.get("id", '')
        official_interaction = request.POST.get("official_interaction", '')
        accompanying_personnel = request.POST.get("accompanying_personnel", '')
        reception_time = request.POST.get("reception_time", '')
        reception_location = request.POST.get("reception_location", '')
        meal_expenses = request.POST.get("meal_expenses", '')
        other_expenses = request.POST.get("other_expenses", '')
        amount_to = request.POST.get("amount_to", '')
        amount_big = request.POST.get("amount_big", '')
        reception_recipients = request.POST.get("reception_recipients", '')
        note = request.POST.get("note", '')
        fj_number = request.POST.get("fj_number", '')

        if flow_id:
            obj = ReceptionChecklist.objects.get(id=int(flow_id))
            obj.official_interaction = official_interaction
            obj.note = note
            obj.reception_time = reception_time
            obj.reception_location = reception_location
            obj.meal_expenses = meal_expenses
            obj.other_expenses = other_expenses
            obj.amount_to = amount_to
            obj.amount_big = amount_big
            obj.reception_recipients = reception_recipients

            obj.receptionchecklistrecord_set.filter(state='unaudit').delete()
            obj.current_audit_users.clear()
        else:
            obj = ReceptionChecklist.objects.create(apply_user=request.user, company=request.user.company, official_interaction=official_interaction,
                                                  note=note, reception_time=reception_time, reception_location=reception_location, meal_expenses=meal_expenses,
                                                  other_expenses=other_expenses, amount_to=amount_to, amount_big=amount_big, reception_recipients=reception_recipients, fj_number=fj_number)

        accompanying_personnel_list = re.findall('\((.*?)\)', accompanying_personnel)
        obj.accompanying_personnel.clear()
        for aaa in accompanying_personnel_list:
            obj.accompanying_personnel.add(User.objects.get(job_number=aaa))

        one_flag = True
        one_step = request.user.company.head_people
        if request.user != one_step:
            ReceptionChecklistRecord.objects.create(parent_id=obj, audit_people=one_step, state='unaudit', audit_note='', node='one')
            obj.state = 'one'
            obj.current_audit_users.add(one_step)
            one_flag = False

        two_step = request.user.company.leaders_id
        ReceptionChecklistRecord.objects.create(parent_id=obj, audit_people=two_step, state='unaudit', audit_note='', node='two')
        if one_flag:
            obj.state = 'two'
            obj.current_audit_users.add(two_step)

        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "公务（外宾）接待清单审批"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.official_interaction[:15] + "……" if len(obj.official_interaction) > 15 else obj.official_interaction
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        obj.save()
        returnDict = {'code': 200, 'message': "操作成功！"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ReceptionChecklistDraft(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        flow_id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = ReceptionChecklist.objects.get(id=int(flow_id))
        audit_dic, flow_dict = {}, {}
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': request.user.real_name, 'position': request.user.post, 'file_list': file_list,
                   'department': request.user.company.name, 'obj': obj, "audit_dic": audit_dic, "reception_time": json.loads(obj.reception_time) if obj.reception_time else {},
                   "reception_recipients": json.loads(obj.reception_recipients) if obj.reception_recipients else [],
                   'revise': revise, "flow_dict": flow_dict, 'accompanying_personnel': ", ".join([f"{i.real_name}({i.job_number})" for i in obj.accompanying_personnel.all()])}
        return render(request, "NewFlowLogic/reception_checklist_draft.html", context)

    def post(self, request):
        flow_id = request.POST.get("id", '')
        official_interaction = request.POST.get("official_interaction", '')
        accompanying_personnel = request.POST.get("accompanying_personnel", '')
        reception_time = request.POST.get("reception_time", '')
        reception_location = request.POST.get("reception_location", '')
        meal_expenses = request.POST.get("meal_expenses", '')
        other_expenses = request.POST.get("other_expenses", '')
        amount_to = request.POST.get("amount_to", '')
        amount_big = request.POST.get("amount_big", '')
        reception_recipients = request.POST.get("reception_recipients", '')
        note = request.POST.get("note", '')
        fj_number = request.POST.get("fj_number", '')

        if flow_id:
            obj = ReceptionChecklist.objects.get(id=int(flow_id))
            obj.official_interaction = official_interaction
            obj.note = note
            obj.reception_time = reception_time
            obj.reception_location = reception_location
            obj.meal_expenses = meal_expenses
            obj.other_expenses = other_expenses
            obj.amount_to = amount_to
            obj.amount_big = amount_big
            obj.reception_recipients = reception_recipients

            obj.receptionchecklistrecord_set.filter(state='unaudit').delete()
            obj.current_audit_users.clear()
        else:
            obj = ReceptionChecklist.objects.create(apply_user=request.user, company=request.user.company,
                                                    official_interaction=official_interaction,
                                                    note=note, reception_time=reception_time,
                                                    reception_location=reception_location, meal_expenses=meal_expenses,
                                                    other_expenses=other_expenses, amount_to=amount_to,
                                                    amount_big=amount_big, reception_recipients=reception_recipients,
                                                    fj_number=fj_number)

        accompanying_personnel_list = re.findall('\((.*?)\)', accompanying_personnel)
        obj.accompanying_personnel.clear()
        for aaa in accompanying_personnel_list:
            obj.accompanying_personnel.add(User.objects.get(job_number=aaa))

        obj.state = "draft"
        obj.save()
        returnDict = {'code': 200, 'message': "保存成功！"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ReceptionChecklistDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        flow_id = request.GET.get('id', None)
        obj = ReceptionChecklist.objects.get(id=int(flow_id))

        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.receptionchecklistrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append(
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.receptionchecklistrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],  "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""), "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, "audit_dic": audit_dic, "flow_dict": flow_dict, "file_list": file_list, "reception_recipients": json.loads(obj.reception_recipients),
                   'is_edit': 'true' if obj.state == 'refuse' and obj.apply_user == request.user else 'false',
                   'is_audit': 'true' if obj.state in ['one', 'two'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'refuse'] and request.user == obj.apply_user else 'false',
                   'accompanying_personnel': ", ".join([i.real_name for i in obj.accompanying_personnel.all()]), "reception_time": json.loads(obj.reception_time),
                   'accompanying_personnel_edit': ", ".join([f"{i.real_name}({i.job_number})" for i in obj.accompanying_personnel.all()]),
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, "NewFlowLogic/reception_checklist_detail.html", context)

    def post(self, request):
        flow_id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "公务（外宾）接待清单审批")
        except:
            pass
        obj = ReceptionChecklist.objects.get(id=int(flow_id))
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.remove(request.user)
        if obj.state == 'one':
            audit_record = obj.receptionchecklistrecord_set.filter(node='one', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_record = obj.receptionchecklistrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.receptionchecklistrecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                obj_state = 'end'
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()

        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class ReceptionChecklistOperation(View):
    def post(self, request):
        operate_type = request.POST.get("operate_type", "")
        flow_id = request.POST.get("id", "")

        flow_obj = ReceptionChecklist.objects.get(id=int(flow_id))
        flow_obj.current_audit_users.clear()
        if operate_type == 'stop':
            flow_obj.state = "stop"
            flow_obj.save()
            message = "终止成功！"
        else:
            flow_obj.audit_users_already.clear()
            flow_obj.receptionchecklistrecord_set.all().delete()
            flow_obj.delete()
            message = "删除成功！"
        returnData = {'code': 200, "status": 'success', 'message': message}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class EmployeesAbroadList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, "NewFlowLogic/employees_abroad_list.html", {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        objs = EmployeesAbroad.objects.filter(apply_user=request.user).order_by('-create_time')
        data_list = [{'id': obj.id, 'application_reason': obj.application_reason, 'entry_time': obj.entry_time,
          'state': obj.get_state_str(), 'join_party_time': obj.join_party_time, 'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
          "url": f"<a href='employees_abroad_draft.html?id={obj.id}'>编辑</a> | <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == 'draft'
          else f"<a href='employees_abroad_detail.html?id={obj.id}'>查看</a> | <a href='employees_abroad_detail.html?revise=true&id={obj.id}'>修改</a>" if obj.can_revise == '1' and obj.state != 'draft' and obj.state != "stop"
          else f"<a href='employees_abroad_detail.html?id={obj.id}'>查看</a> |  <a href='javascript:' onclick='del_draft({obj.id})' style='color:red'>删除</a>" if obj.state == "stop" else f"<a href='employees_abroad_detail.html?id={obj.id}'>查看</a>",
          }
         for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class EmployeesAbroadIndex(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        fj_number = uuid.uuid4()
        return render(request, "NewFlowLogic/employees_abroad_index.html", {'realname': real_name, 'position': position, 'department': department, 'job_number': request.user.job_number, "uuid": fj_number})

    def post(self, request):
        flow_id = request.POST.get("id", '')
        entry_time = request.POST.get("entry_time", '')
        join_party_time = request.POST.get("join_party_time", '')
        position = request.POST.get("position", '')
        onwards_country = request.POST.get("onwards_country", '')
        position_identity = request.POST.get("position_identity", '')
        mailing_address_ch = request.POST.get("mailing_address_ch", '')
        mailing_address_en = request.POST.get("mailing_address_en", '')
        application_reason = request.POST.get("application_reason", '')
        social_relations_ch = request.POST.get("social_relations_ch", '')
        social_relations_en = request.POST.get("social_relations_en", '')
        restrictive_conditions = request.POST.get("restrictive_conditions", '')
        fj_number = request.POST.get("fj_number", '')

        if flow_id:
            obj = EmployeesAbroad.objects.get(id=int(flow_id))
            obj.entry_time = entry_time
            obj.join_party_time = join_party_time
            obj.position = position
            obj.onwards_country = onwards_country
            obj.position_identity = position_identity
            obj.mailing_address_ch = mailing_address_ch
            obj.mailing_address_en = mailing_address_en
            obj.application_reason = application_reason
            obj.social_relations_ch = social_relations_ch
            obj.social_relations_en = social_relations_en
            obj.restrictive_conditions = restrictive_conditions

            obj.employeesabroadrecord_set.filter(state='unaudit').delete()
            obj.current_audit_users.clear()
        else:
            obj = EmployeesAbroad.objects.create(apply_user=request.user, company=request.user.company, entry_time=entry_time, join_party_time=join_party_time, social_relations_en=social_relations_en,
                                                 position=position, onwards_country=onwards_country, position_identity=position_identity, mailing_address_ch=mailing_address_ch, restrictive_conditions=restrictive_conditions,
                                                mailing_address_en=mailing_address_en, application_reason=application_reason, social_relations_ch=social_relations_ch, fj_number=fj_number)


        one_flag = True
        one_step = request.user.company.head_people
        if request.user != one_step:
            EmployeesAbroadRecord.objects.create(parent_id=obj, audit_people=one_step, state='unaudit', audit_note='', node='one')
            obj.state = 'one'
            obj.current_audit_users.add(one_step)
            one_flag = False

        two_step = Company.objects.get(id=18).head_people
        EmployeesAbroadRecord.objects.create(parent_id=obj, audit_people=two_step, state='unaudit', audit_note='', node='two')
        if one_flag:
            obj.state = 'two'
            obj.current_audit_users.add(two_step)

        if position in ['1', '2', '3', '4']:
            if position_identity == '1':
                three_step = Company.objects.get(id=3).head_people
            elif position_identity == '2':
                three_step = Company.objects.get(id=13).head_people
            else:
                three_step = Company.objects.get(id=15).head_people
            EmployeesAbroadRecord.objects.create(parent_id=obj, audit_people=three_step, state='unaudit', audit_note='', node='three')
            four_step = request.user.company.leaders_id
            EmployeesAbroadRecord.objects.create(parent_id=obj, audit_people=four_step, state='unaudit', audit_note='', node='four')

        five_step = Company.objects.get(id=16).head_people
        EmployeesAbroadRecord.objects.create(parent_id=obj, audit_people=five_step, state='unaudit', audit_note='', node='five')

        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "职工出国(境)审批"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.application_reason[:15] + "……" if len(obj.application_reason) > 15 else obj.application_reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        obj.save()
        returnDict = {'code': 200, 'message': "操作成功！"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class EmployeesAbroadDraft(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        flow_id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = EmployeesAbroad.objects.get(id=int(flow_id))
        audit_dic, flow_dict = {}, {}
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': request.user.real_name, 'position': request.user.post, 'file_list': file_list, 'department': request.user.company.name, 'obj': obj, "audit_dic": audit_dic,
                   'revise': revise, "flow_dict": flow_dict}
        return render(request, "NewFlowLogic/employees_abroad_draft.html", context)

    def post(self, request):
        flow_id = request.POST.get("id", '')
        entry_time = request.POST.get("entry_time", '')
        join_party_time = request.POST.get("join_party_time", '')
        position = request.POST.get("position", '')
        onwards_country = request.POST.get("onwards_country", '')
        position_identity = request.POST.get("position_identity", '')
        mailing_address_ch = request.POST.get("mailing_address_ch", '')
        mailing_address_en = request.POST.get("mailing_address_en", '')
        application_reason = request.POST.get("application_reason", '')
        social_relations_ch = request.POST.get("social_relations_ch", '')
        social_relations_en = request.POST.get("social_relations_en", '')
        restrictive_conditions = request.POST.get("restrictive_conditions", '')
        fj_number = request.POST.get("fj_number", '')

        if flow_id:
            obj = EmployeesAbroad.objects.get(id=int(flow_id))
            obj.entry_time = entry_time
            obj.join_party_time = join_party_time
            obj.position = position
            obj.onwards_country = onwards_country
            obj.position_identity = position_identity
            obj.mailing_address_ch = mailing_address_ch
            obj.mailing_address_en = mailing_address_en
            obj.application_reason = application_reason
            obj.social_relations_ch = social_relations_ch
            obj.social_relations_en = social_relations_en
            obj.restrictive_conditions = restrictive_conditions

            obj.employeesabroadrecord_set.filter(state='unaudit').delete()
            obj.current_audit_users.clear()
        else:
            obj = EmployeesAbroad.objects.create(apply_user=request.user, company=request.user.company, entry_time=entry_time, join_party_time=join_party_time,
                                                 social_relations_en=social_relations_en, position=position, onwards_country=onwards_country, position_identity=position_identity,
                                                 mailing_address_ch=mailing_address_ch, restrictive_conditions=restrictive_conditions, mailing_address_en=mailing_address_en,
                                                 application_reason=application_reason, social_relations_ch=social_relations_ch, fj_number=fj_number)

        obj.state = "draft"
        obj.save()
        returnDict = {'code': 200, 'message': "保存成功！"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class EmployeesAbroadDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        flow_id = request.GET.get('id', None)
        obj = EmployeesAbroad.objects.get(id=int(flow_id))

        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.employeesabroadrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append(
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.employeesabroadrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                     'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, "audit_dic": audit_dic, "flow_dict": flow_dict, "file_list": file_list,
                   'is_edit': 'true' if obj.state == 'refuse' and obj.apply_user == request.user else 'false',
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'refuse'] and request.user == obj.apply_user else 'false',
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, "NewFlowLogic/employees_abroad_detail.html", context)

    def post(self, request):
        flow_id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "职工出国(境)审批")
        except:
            pass
        obj = EmployeesAbroad.objects.get(id=int(flow_id))
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.remove(request.user)
        if obj.state == 'one':
            audit_record = obj.employeesabroadrecord_set.filter(node='one', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_record = obj.employeesabroadrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.employeesabroadrecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.employeesabroadrecord_set.filter(node='three').count():
                    next_audit_record = obj.employeesabroadrecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
                else:
                    next_audit_record = obj.employeesabroadrecord_set.filter(node='five', state='unaudit').first()
                    obj_state = 'five'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.employeesabroadrecord_set.filter(node='three', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_record = obj.employeesabroadrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            audit_record = obj.employeesabroadrecord_set.filter(node='four', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_record = obj.employeesabroadrecord_set.filter(node='five', state='unaudit').first()
                obj_state = 'five'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'five':
            audit_record = obj.employeesabroadrecord_set.filter(node='five', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                obj_state = 'end'
            else:
                obj_state = 'refuse'
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()

        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class EmployeesAbroadOperation(View):
    def post(self, request):
        operate_type = request.POST.get("operate_type", "")
        flow_id = request.POST.get("flow_id", "")

        flow_obj = EmployeesAbroad.objects.get(id=int(flow_id))
        flow_obj.current_audit_users.clear()
        if operate_type == 'stop':
            flow_obj.state = "stop"
            flow_obj.save()
            message = "终止成功！"
        else:
            flow_obj.audit_users_already.clear()
            flow_obj.employeesabroadrecord_set.all().delete()
            flow_obj.delete()
            message = "删除成功！"
        returnData = {'code': 200, "status": 'success', 'message': message}
        return HttpResponse(json.dumps(returnData), content_type="application/json")